﻿using parkMonitor.model;
using parkMonitor.viewModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace parkMonitor.server
{
    /// <summary>Pc状态监控范围</summary>
    public class PcStatusServer
    {
        public static readonly PcStatusServer ins = new PcStatusServer();

        Timer timer = null;
        int timerGap = 2000;
        PerformanceCounter cpuCounter = null;
        PerformanceCounter freeMemCounter = null;
        Int64 totalMemory = 1;

        public void start()
        {
            initCounter();

            stop();
            timer = new Timer((data) =>
            {
                onTimer(data);
            }, null, 0, timerGap);
        }

        private void initCounter()
        {
            if (cpuCounter != null)
            {
                return;
            }

            //cpu
            cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            //内存
            freeMemCounter = new PerformanceCounter();
            freeMemCounter.CategoryName = "Memory";
            freeMemCounter.CounterName = "Available Bytes";
            freeMemCounter.InstanceName = "";

            //总内存
            totalMemory = Math.Max(GetTotalMemory(), 1);
        }

        public static Int64 GetTotalMemory()
        {
            try
            {
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if (mo["TotalPhysicalMemory"] != null)
                    {
                        return long.Parse(mo["TotalPhysicalMemory"].ToString());
                    }
                }
            }
            catch (Exception)
            {

            }

            return 1;
        }

        private void onTimer(object data)
        {
            float cpu = cpuCounter.NextValue();
            float mem = freeMemCounter.NextValue();
            mem = (totalMemory - mem) / totalMemory * 100;

            UIFace ui = UIFace.ins;

            ui.syncCtl(() =>
            {
                ui.cpu = (int)cpu;
                ui.mem = (int)mem;
            });
        }

        public void stop()
        {
            if (timer != null)
            {
                timer.Dispose();
                timer = null;
            }
        }
    }
}
